﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApiTest.Dto.Basic;
using WebApiTest.Dto.Utils;
using WebApiTest.Models;
using Type = WebApiTest.Models.Type;

namespace WebApiTest.Service.Office

{
    public class TypeService
    {
        officeContext db = new officeContext();

        public TableRspDTO list4Table(TableReqDTO tableReqDTO)
        {
            long count = db.Type
                .Where(u => string.IsNullOrEmpty(tableReqDTO.parseQueryParam("typeName")) || u.TypeName.Contains(tableReqDTO.parseQueryParam("typeName")))
                .LongCount();
            List<JObject> res = db.Type
                .Select(u => new { key = u.TypeId, typeId = u.TypeId, typeName = u.TypeName })
                .Where(u => string.IsNullOrEmpty(tableReqDTO.parseQueryParam("typeName")) || u.typeName.Contains(tableReqDTO.parseQueryParam("typeName")))
                .OrderByDescending(u => u.typeId)
                .Skip(tableReqDTO.getStart())
                .Take(tableReqDTO.pageSize)
                .ToList()
                .ConvertAll(r => JObject.FromObject(r));
            PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.pageNo,
                tableReqDTO.pageSize,
                count,
                res
                );
            return new TableRspDTO(pagingDTO);
        }

        public int add(Type type)
        {
            db.Type.Add(type);
            db.SaveChanges();
            return 1;
        }

        public int update(Type type)
        {
            Type o = db.Type.Find(type.TypeId);
            o.TypeName = type.TypeName;
            db.SaveChanges();
            return 1;
        }
        public int remove(string ids)
        {
            List<Type> list = new List<Type>();
            string[] idList = ids.Split(",");
            foreach (string id in idList)
            {
                list.Add(db.Type.Find(long.Parse(id)));
            }
            db.Type.RemoveRange(list);
            //更新到数据库
            db.SaveChanges();
            return list.Count();
        }

        public List<JObject> listAll()
        {
            return db.Type
                .Select(e => new { typeId = e.TypeId, typeName = e.TypeName })
                .ToList()
                .ConvertAll(e => JObject.FromObject(e)); 
        }

    }
}
